
const widgeon = require("widgeon");
const xpcom = require("xpcom");
require("uri-policy");

// Components.utils.import("resource://gre/modules/NetUtil.jsm");
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");

const SCHEME = "widget";

function WidgetSchemeHandler () {}
WidgetSchemeHandler.prototype = {
    scheme: SCHEME,
    defaultPort: -1,
    protocolFlags: Ci.nsIProtocolHandler.URI_STD,

    newURI: function WSH_newURI (spec, charset, baseURI) {
        var nssu = Ci.nsIStandardURL;
        var url = Components.classes["@mozilla.org/network/standard-url;1"].createInstance(nssu);
        url.init(nssu.URLTYPE_STANDARD, -1, spec, charset, baseURI);
        return url.QueryInterface(Ci.nsIURI);
    },

    newChannel: function WSH_newChannel (uri) {
        if (!uri.schemeIs("widget")) return;
        var widget = widgeon.createWidget(uri.host);
        if (uri.path == "/config.xml") return this.errorChannel("Forbidden: " + uri.spec, uri);
        // XXX maybe other forbiddens
        var path = uri.path.replace(/^\//, "");
        var jarURI = widget.file(path);
        var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
        var channel = ios.newChannel(jarURI, null, null);
        channel.originalURI = uri;
        return channel;
    },
    
    allowPort: function WSH_allowPort (aPort, aScheme) {
        return false;
    },
    
    errorChannel:    function (error, uri) {
        console.log("errorChannel=" + error);
        var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
        var channel = ios.newChannel('data:text/html;charset=utf-8,<!DOCTYPE html>%0D%0A<html lang%3D"en">%0D%0A <head><title>Error<%2Ftitle><%2Fhead>%0D%0A <body>%0D%0A  <pre style="color: red">ERROR:\n' + error + '<%2Fpre>%0D%0A <%2Fbody>%0D%0A<%2Fhtml>%0D%0A', null, null);
        // channel = ios.newChannel(fileURI, null, null);
        return channel;
    },

    classDescription: "Widget Scheme Handler",
    contractID: "@mozilla.org/network/protocol;1?name=" + SCHEME,
    classID: Components.ID("{cc5875c0-0e37-48ac-a842-83f6b69574de}"),
    QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler]),
};

xpcom.register({
    create:     WidgetSchemeHandler,
    name:       WidgetSchemeHandler.prototype.classDescription,
    contractID: WidgetSchemeHandler.prototype.contractID,
    uuid:       WidgetSchemeHandler.prototype.classID
});
